package com.liuya.session.provider;

import com.github.pagehelper.PageInfo;
import com.liuya.base.AbstractBaseProvider;
import com.liuya.common.InstanceUtil;
import com.liuya.common.PropertiesUtil;
import com.liuya.common.support.dubbo.spring.annotation.DubboService;
import com.liuya.session.dao.SysSessionMapper;
import com.liuya.session.model.SysSession;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author liuya
 * @date 20160907
 */
//@CacheConfig(cacheNames = "sysSessionProvider")
@DubboService(interfaceClass = SysSessionProvider.class, interfaceName = "sysSessionProvider")
public class SysSessionProviderImpl extends AbstractBaseProvider<SysSession> implements SysSessionProvider {

    @Autowired
    private SysSessionMapper sysSessionMapper;

//    @CachePut
//    @Transactional
    public SysSession update(SysSession record) {
        if (record.getId() == null) {
            record.setUpdateBy(record.getLoginName());
            record.setUpdateTime(new Date());
            String id = sysSessionMapper.queryBySessionId(record.getSessionId());
            if (StringUtils.isNotBlank(id)) {
                record.setId(id);
                sysSessionMapper.updateByPrimaryKey(record);
            } else {
                record.setId(createId("SysSession"));
                record.setCreateBy(record.getLoginName());
                record.setCreateTime(new Date());
                sysSessionMapper.insert(record);
            }
        } else {
            sysSessionMapper.updateByPrimaryKey(record);
        }
        return record;
    }

//    @CacheEvict
    public void delete(final String id) {
        sysSessionMapper.deleteByPrimaryKey(id);
    }

    // 系统触发,由系统自动管理缓存
    public void deleteBySessionId(final String sessionId) {
        sysSessionMapper.deleteBySessionId(sessionId);
    }

    public List<String> querySessionIdByAccount(String account) {
        return sysSessionMapper.querySessionIdByAccount(account);
    }

    public void cleanExpiredSessions() {
        String key = "spring:session:" + PropertiesUtil.getString("session.redis.namespace") + ":sessions:expires:";
        Map<String, Object> columnMap = InstanceUtil.newHashMap();
//        List<String> ids = sysSessionMapper.selectIdByMap(new RowBounds(), columnMap);
//        List<SysSession> sessions = getList(ids);
//        for (SysSession sysSession : sessions) {
//            logger.info("检查SESSION : {}", sysSession.getSessionId());
//            if (!JedisUtil.exists(key + sysSession.getSessionId())) {
//                logger.info("移除SESSION : {}", sysSession.getSessionId());
//                sysSessionMapper.deleteByPrimaryKey(sysSession.getId());
//            }
//        }
    }
}
